#!/bin/bash
export PATH=/d/apps/erl-27.3/bin:${PATH}


DIR_ROOT=$(dirname $(readlink -f $0))/

BEAM="deps/*/ebin/ ebin"
MNESIA_ARGS="-mnesia dump_log_write_threshold 100000"


fun_dev()
{
	cd ${DIR_ROOT}

    # 如果 ebin 目录存在，编译完后会把它下面的文件复制到编译后对应的 ebin 目录
	rm -f ebin/*

	rebar3 as dev compile
	_copy_compile_file dev
}

fun_prod()
{
	cd ${DIR_ROOT}

	# 如果 ebin 目录存在，编译完后会把它下面的文件复制到编译后对应的 ebin 目录
    rm -f ebin/*

	rebar3 as prod compile
	_copy_compile_file prod
}


fun_start()
{
    cd ${DIR_ROOT}

    dirVar="var/"
    dirMnesia="${dirVar}mnesia"
    fileConf="app.conf"

    mkdir -p ${dirVar}

    start erl -pa ${BEAM} -hidden -name "app@127.0.0.1" -config ./sys.config +P 1024000 -mnesia dir \"${dirMnesia}\" ${MNESIA_ARGS} -s main start -extra server_tpl ${dirVar} ${fileConf}
}

fun_up()
{
    cd ${DIR_ROOT}

    erl -pa ${BEAM} -hidden -name "app_up@127.0.0.1" -noshell -eval "rpc:call('app@127.0.0.1', dev, up, []), erlang:halt()."
}

fun_stop()
{
    cd ${DIR_ROOT}

    erl -pa ${BEAM} -hidden -name "app_stop@127.0.0.1" -noshell -s main stop -extra "app@127.0.0.1"
}

fun_stop_backup()
{
    cd ${DIR_ROOT}

    erl -pa ${BEAM} -hidden -name "app_stop@127.0.0.1" -noshell -s main stop_and_backup -extra "app@127.0.0.1"
}


fun_help()
{
    echo "dev                 编译开发版"
    echo "prod                编译生产版"
    echo

    echo "start               启动服务器"
    echo "up                  热更服务器"
    echo "stop                关闭服务器"
    echo "stop_backup         关闭服务器并备份"
	echo

    exit 1
}


_copy_compile_file()
{
    mode=$1

    mkdir -p deps/ ebin/

    cp -f _build/${mode}/lib/app/ebin/* ebin/

    for dir in "_build/default/lib"/*/; do
        dirName=$(basename $dir)
        if [ "$dirName" == "app" ]; then
            continue
        fi

        mkdir -p deps/${dirName}/
        cp -r ${dir}ebin/ deps/${dirName}/
    done
}



if [ $# -eq 0 ]
then
	fun_help
else
	fun_$1 $*
fi

exit 0
